<template>
  <el-card>
    <el-form inline class="forms">
      <el-form-item label="职位名称">
        <el-input
          placeholder="请输入职位名称关键字"
          v-model="roleName"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="search"
          :disabled="roleName ? false : true"
          >搜索</el-button
        >
        <el-button type="danger" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0">
    <el-button
      type="primary"
      icon="Plus"
      @click="addRole"
      v-has="`btn.Role.add`"
      >添加职位</el-button
    >
    <el-table border style="margin: 10px 0px" :data="roleArr">
      <el-table-column label="#" type="index" align="center"></el-table-column>
      <el-table-column label="id" align="center" prop="id"></el-table-column>
      <el-table-column
        label="角色名称"
        align="center"
        show-overflow-tooltip
        prop="roleName"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
      ></el-table-column>
      <el-table-column label="操作" align="center" width="300px">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="user"
            @click="toAssign(row)"
            v-has="`btn.Role.assgin`"
            >分配权限</el-button
          >
          <el-button
            type="info"
            size="small"
            icon="Edit"
            @click="toEdit(row)"
            v-has="`btn.Role.update`"
            >编辑</el-button
          >

          <el-popconfirm
            :title="`你确定删除${row.roleName}吗?`"
            @confirm="DeleteRole(row)"
            width="260px"
          >
            <template #reference>
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                v-has="`btn.Role.remove`"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <el-dialog
      v-model="dialogFormVisible"
      :title="roleParmas.id ? '修改职位' : '新增职位'"
    >
      <template #default>
        <el-form :model="roleParmas" :rules="rulus" ref="from">
          <el-form-item label="职位名称" prop="roleName">
            <el-input
              placeholder="请输入职位名称"
              v-model="roleParmas.roleName"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="AddOrUpdatRole">确定</el-button>
        <el-button type="danger" @click="cancel">取消</el-button>
      </template>
    </el-dialog>
    <!-- 抽屉组件 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配职位权限</h4>
      </template>
      <template #default>
        <!-- 树形节点组件
          data展示的数据
          show-checkbox 节点是否可被选择
          node-key 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的
          default-expanded-keys 默认展开的节点的 key 的数组
          default-checked-keys 默认选中的节点的 key 的数组
          props 配置选项
          default-expand-all 是否默认展开所有节点
        -->
        <el-tree
          :data="MenuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="roleIds"
          :props="defaultProps"
          ref="tree"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
//引入类型
import type {
  reqRoleResponese,
  records,
  reqRoleMenuResponeseData,
  MenuList,
} from "@/api/acl/role/type";
//引入接口
import {
  getAllPosition,
  addOrUpdatePosition,
  getPositionByUserId,
  assignPosition,
  deletePostion,
} from "@/api/acl/role/index.ts";
import { ElMessage } from "element-plus";

let pageNo = ref<number>(1);
let pageSize = ref<number>(5);
//职位名称
let roleName = ref<string>("");
//收集全部数据数组
let roleArr = ref<records>([]);
//数据总条数
let total = ref<number>(0);
//控制对话框的显示与隐藏
let dialogFormVisible = ref<boolean>(false);
//获取表单组件
let from = ref<any>();
//控制抽屉的显示与隐藏
let drawer = ref<boolean>(false);
//tree组件
let tree = ref<any>();
//收集职位数据
let roleParmas = reactive<any>({
  roleName: "",
});
//收集过滤出来的id
let roleIds = ref<number[]>([]);
//收集全部权限数据
let MenuArr = ref<MenuList>([]);
//获取全部数据方法
const HasAllRole = async (page = 1) => {
  pageNo.value = page;
  let result: reqRoleResponese = await getAllPosition(
    pageNo.value,
    pageSize.value,
    roleName.value,
  );
  if (result.code == 200) {
    //收集数据
    roleArr.value = result.data.records;
    total.value = result.data.total;
  }
};
//挂载时获取全部数据
onMounted(() => {
  HasAllRole();
});
//当前页数发生变化时的回调
const handleCurrentChange = (value: number) => {
  //调用方法
  HasAllRole(value);
};
//每页展示多少条数据发生改变时调用
const handleSizeChange = (value: number) => {
  //收集数据
  pageSize.value = value;
  //调用方法
  HasAllRole();
};
//搜索按钮
const search = () => {
  //调用方法
  HasAllRole();
  //清空数据
  roleName.value = "";
};
//重置按钮
const reset = () => {
  //调用方法
  HasAllRole();
};
//添加职位按钮回调
const addRole = () => {
  //显示对话框
  dialogFormVisible.value = true;
  //清除上次数据
  Object.assign(roleParmas, {
    roleName: "",
    id: 0,
  });
  //调用组件方法清空验证消息
  nextTick(() => {
    from.value.clearValidate("roleName");
  });
};
//取消按钮的回调
const cancel = () => {
  // 隐藏对话框
  dialogFormVisible.value = false;
};
//编辑按钮的回调
const toEdit = (row: any) => {
  //显示对话框
  dialogFormVisible.value = true;
  //整理数据
  Object.assign(roleParmas, row);
  //清除组件校验信息
  nextTick(() => {
    from.value.clearValidate("roleName");
  });
};
//表单规则校验对象
const rulus = {
  roleName: [
    { required: true, message: "请输入职位名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
};
//添加职位或者修改职位的回调
const AddOrUpdatRole = async () => {
  //发请求
  let result = await addOrUpdatePosition(roleParmas);
  if (result.code == 200) {
    //提示
    ElMessage({
      type: "success",
      message: roleParmas.id ? "修改成功" : "添加成功",
    });
    //关闭对话框
    dialogFormVisible.value = false;
    //再次获取数据
    HasAllRole(roleParmas.id ? pageNo.value : 1);
  } else {
    ElMessage({
      type: "error",
      message: roleParmas.id ? "修改失败" : "添加失败",
    });
  }
};
//分配权限按钮回调
const toAssign = async (row: any) => {
  //清除上一次的id数组
  roleIds.value = [];
  //显示抽屉
  drawer.value = true;
  //收集数据
  Object.assign(roleParmas, row);
  //发请求
  let result: reqRoleMenuResponeseData = await getPositionByUserId(
    roleParmas.id,
  );
  if (result.code == 200) {
    //收集数据
    MenuArr.value = result.data;
    //调用函数过滤数据
    roleIds.value = filterMenu(MenuArr.value, []);
  }
};
//递归函数过滤数据
const filterMenu = (MenuList: any, initArr: any) => {
  MenuList.forEach((item: any) => {
    if (item.select == true && item.level == 4) {
      initArr.push(item.id);
    }
    if (item.children && item.children.length > 0) {
      filterMenu(item.children, initArr);
    }
  });
  return initArr;
};
//树形组件数据
const defaultProps = {
  children: "children",
  label: "name",
};
//抽屉确定按钮的回调
const handler = async () => {
  //收集数据
  const roleId = roleParmas.id;
  let arr = tree.value.getCheckedKeys();
  let arr1 = tree.value.getHalfCheckedNodes();
  //合并两个数组
  let permissionId = arr.concat(arr1.map((item: any) => item.id));

  //发请求
  let result = await assignPosition(roleId, permissionId);
  if (result.code == 200) {
    //关闭抽屉
    drawer.value = false;
    //提示信息
    ElMessage({
      type: "success",
      message: "分配成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "分配失败",
    });
  }
  //刷新页面
  window.location.reload();
};
//删除按钮的回调
const DeleteRole = async (row: any) => {
  let result = await deletePostion(row.id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    //获取数据
    HasAllRole(roleArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
  }
};
</script>

<style scoped lang="scss">
.forms {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
